<template>
  <van-card
      v-for="team in props.teamList"
      :key="team.id"
      :thumb="partner"
      :desc="team.description"
      :title="`${team.name}`"
  >
    <template #tags>
      <van-tag plain type="primary" style="margin-right: 8px;margin-top: 8px">
        {{ teamStatusEnum[team.status] }}
      </van-tag>
    </template>
    <template #bottom>
      <div>
        {{ `队伍人数: ${team.hasJoinNum}/${team.maxNum} `}}
        <!--:pivot-text="`队伍人数: ${team.hasJoinNum}/${team.maxNum} | ${(team.hasJoinNum/team.maxNum)*100}%`"-->
        <van-progress  :percentage="(team.hasJoinNum / team.maxNum) * 100" stroke-width="8" style="margin:5px 5px"/>
      </div>
      <div>
        <span v-html="`创建时间: <strong>${formatDate(team.createTime)}</strong>`"/>
      </div>
      <div v-if="team.expireTime">
        <span v-html="`过期时间: <strong>${formatDate(team.expireTime)}</strong>`"/>
        <van-count-down :time="getCountdownTime(team.expireTime)" format="DD 天 HH 时 mm 分 ss 秒">
          <template #default="timeData">
            <template
                v-if="timeData.days === 0 && timeData.hours === 0 && timeData.minutes === 0 && timeData.seconds === 0">
              <span class="colon">已过期</span>
            </template>
            <template v-else>
              <van-icon name="fire-o" color="#ee0a24" style="padding-right: min(0.5rem, 1vw)"/>
              <span class="block">{{ timeData.days }}</span>
              <span class="colon">天</span>
              <span class="block">{{ timeData.hours }}</span>
              <span class="colon">小时</span>
              <span class="block">{{ timeData.minutes }}</span>
              <span class="colon">分</span>
              <span class="block">{{ timeData.seconds }}</span>
              <span class="colon">秒</span>
            </template>
          </template>
        </van-count-down>
      </div>

    </template>
    <template #footer>
      <van-button size="small" type="primary" v-if="team.userId !== currentUser?.id && !team.hasJoin"
                  plain
                  style="margin-top: 8px;"
                  @click="preJoinTeam(team)"
      >加入队伍
      </van-button>
      <van-button v-if="team.userId === currentUser?.id" size="small" plain color="#7232dd"
                  @click="doUpdateTeam(team.id)" style="margin-top: 8px;">更新队伍
      </van-button>
      <!--仅加入队伍可见-->
      <van-button
          v-if="team.userId !== currentUser?.id && team.hasJoin"
          size="small" plain type="warning"
          @click="doQuitTeam(team.id)" style="margin-top: 8px;">退出队伍
      </van-button>
      <van-button v-if="team.userId === currentUser?.id" size="small" plain type="danger"
                  @click="doDeleteTeam(team.id)" style="margin-top: 8px;">解散队伍
      </van-button>
    </template>
  </van-card>
  <van-dialog v-model:show="showPasswordDialog" title="请输入密码" show-cancel-button @confirm="doJoinTeam"
              @cancel="doJoinCancel">
    <van-field v-model="password" type="password" placeholder="请输入房间密码"/>
  </van-dialog>

</template>

<script setup lang="ts">
import {TeamType} from "../models/team";
import {teamStatusEnum} from "../constants/team.ts";
import partner from '../assets/partner.png';
import myAxios from "../plugins/myAxios.ts";
import {showFailToast, showSuccessToast} from "vant";
import {onMounted, ref} from "vue";
import {getCurrentUser} from "../services/user.ts";
import {useRouter} from "vue-router";

interface TeamCardListProps {
  teamList: TeamType[];
}

const showPasswordDialog = ref(false);
const password = ref('')
const joinTeamId = ref();
const props = withDefaults(defineProps<TeamCardListProps>(), {
  teamList: () => []
})

const currentUser = ref();
const router = useRouter();

onMounted(async () => {
  currentUser.value = await getCurrentUser();
})

const preJoinTeam =
    (team: TeamType) => {
      joinTeamId.value = team.id
      if (team.status === 0) {
        doJoinTeam()
      } else {
        showPasswordDialog.value = true;
      }
    }

const doJoinCancel = () => {
  joinTeamId.value = 0
  password.value = ''
}

/**
 * 加入队伍
 */
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    showFailToast('请选择要加入的队伍');
    return;
  }
  const res = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value
  });
  if (res.data?.code === 0) {
    showSuccessToast('加入成功');
    // 更新本地 teamList
    const updatedTeam = props.teamList.find(team => team.id === joinTeamId.value);
    if (updatedTeam) {
      updatedTeam.hasJoin = true;
    }
    doJoinCancel();
    router.go(0)
  } else {
    showFailToast('加入失败' + (res.data.description ? `,${res.data.description}` : ''));
    doJoinCancel();
  }
}

/**
 * 跳转至更新队伍
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      id,
    }
  })
}

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  if (res.data?.code === 0) {
    showSuccessToast('操作成功');
    // 更新本地 teamList
    const updatedTeam = props.teamList.find(team => team.id === id);
    if (updatedTeam) {
      updatedTeam.hasJoin = false;
    }
    router.go(0)
  } else {
    showFailToast('操作失败' + (res.data.description ? `,${res.data.description}` : ''));
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res = await myAxios.post('/team/delete', {
    id
  });
  if (res.data?.code === 0) {
    showSuccessToast('操作成功');
    //刷新页面
    router.go(0);
  } else {
    showFailToast('操作失败' + (res.data.description ? `,${res.data.description}` : ''));
  }
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleString();
};

const getCountdownTime = (expireTime: string) => {
  return Date.parse(expireTime) - Date.now();
};

</script>

<style>
.colon {
  display: inline-block;
  margin: 0 4px;
  color: #1989fa;
}

.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: #1989fa;
}
</style>
